package com.sa07.ui.window;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

import com.sa07.bean.Role;
import com.sa07.bean.User;
import com.sa07.config.IConfigInitManager;
import com.sa07.config.LoginSession;
import com.sa07.exception.DatabaseExecuteFailedException;
import com.sa07.resources.ResourceUtils;
import com.sa07.role.service.IRoleService;
import com.sa07.role.service.RoleService;
import com.sa07.ui.bean.Item;
import com.sa07.ui.config.AsynConfigInitManager;
import com.sa07.ui.uitls.UiTools;
import com.sa07.user.service.IUserService;
import com.sa07.user.service.Userservice;
import com.sa07.utils.StringUtils;

/**
 * 登录窗口
 * 
 * @author Long.shangbo
 * 
 *         2014-2-14 下午10:20:43
 */
public class LoginWindow extends JFrame {

	private static final long serialVersionUID = -8959375661052625506L;

	private static final String TOP_IMG = "login.jpg";
	
	private static final int WIN_HEIGHT = 330;

	private Icon topImg = null;
	
	private JComboBox userTypeCom = null;
	
	private JComboBox userNameCom = null;
	
	private JPasswordField userPwdTxt = null;

	private JButton loginBtn = null;

	private JButton exitBtn = null;

	private JFrame loginWin = this;
	
	private FutureTask<Boolean> initTask = null;
	
	private IUserService userService = new Userservice();

	public LoginWindow() {
		setTitle("作业员登录");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		topImg = ResourceUtils.getIcon(TOP_IMG);
		setSize(new Dimension(topImg.getIconWidth(), WIN_HEIGHT));
		setBackground(Color.WHITE);
		setResizable(false);
		setLocation(UiTools.getCenterPosition(topImg.getIconWidth(), WIN_HEIGHT));
		setLayout(null);
		
		//启动线程去初始化任务
		initTask = new FutureTask<Boolean>(new Callable<Boolean>() {

			@Override
			public Boolean call() throws Exception {
				// 启动加载配置
				IConfigInitManager configManager = new AsynConfigInitManager();
				configManager.init();
				return true;
			}
		});
		
		new Thread(initTask).start();
	}

	/**
	 * 启动窗口
	 */
	public void launch() {
		// 初始化组件
		try {
			initComponents();
		} catch (DatabaseExecuteFailedException e) {
			JOptionPane.showMessageDialog(null, "数据初始化失败!");
			return;
		}
		// 初始化事件
		initListener();
		
		setVisible(true);
	}

	/**
	 * 获得用户下拉框数据
	 * @throws DatabaseExecuteFailedException 
	 */
	private Item[] getUserComboxData() throws DatabaseExecuteFailedException {
		List<User> userList = userService.queryAllUser();
		Item[] userItems = null;
		
		if(userList != null){
			userItems = new Item[userList.size()];
			Item item = null;
			User user = null;
			
			for(int i = 0; i < userList.size(); i++){
				user = userList.get(i);
				item = new Item();
				item.setValue(user.getUserId());
				item.setDisplay(user.getUserName());
				userItems[i] = item;
			}
		}
		
		return userItems;
	}
	
	/**
	 * 获得用户类型下拉框数据
	 * @throws DatabaseExecuteFailedException 
	 */
	private Item[] getUserTypeComboxData() throws DatabaseExecuteFailedException {
		IRoleService roleService = new RoleService();
		List<Role> roles = roleService.queryAllRole(); 
		Item[] roleItem = null;
		
		if(roles != null){
			roleItem = new Item[roles.size()];
			Item item = null;
			Role role = null;
			
			for(int i = 0; i < roles.size(); i++){
				role = roles.get(i);
				item = new Item();
				item.setValue(role.getRoleId());
				item.setDisplay(role.getRoleName());
				roleItem[i] = item;
			}
		}
		
		return roleItem;
	}

	/**
	 * 初始化监听
	 */
	private void initListener() {
		// 退出
		exitBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		// 登录
		loginBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String userPwd = String.valueOf(userPwdTxt.getPassword()).trim();
				
				if(StringUtils.isNullOrEmpty(userPwd)){
					JOptionPane.showMessageDialog(null, "请输入密码！", "温馨提示", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				int roleId = Integer.parseInt(((Item) userTypeCom
						.getSelectedItem()).getValue().toString());
				int userId = Integer.parseInt(((Item) userNameCom
						.getSelectedItem()).getValue().toString());
				
				User user = null;
				
				try {
					user = userService.login(userId, roleId, userPwd);
					LoginSession.INSTANCE.setUser(user);
				} catch (DatabaseExecuteFailedException e1) {
					JOptionPane.showMessageDialog(null, "系统异常，登录失败！", "温馨提示", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				if(user == null){
					JOptionPane.showMessageDialog(null, "登录失败，用户名或密码或角色错误!", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
					return;
				}
				
				//等待配置初始化成功再进入主界面
				try {
					initTask.get();
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "系统异常，配置初始化失败！", "温馨提示", JOptionPane.ERROR_MESSAGE);
					return;
				}
				
				MainFrame mainDialog = new MainFrame();
				mainDialog.launch();
				mainDialog.init();
				loginWin.dispose();
			}
		});
	}

	/**
	 * 初始化组件
	 * @throws DatabaseExecuteFailedException 
	 */
	private void initComponents() throws DatabaseExecuteFailedException {
		JLabel backgroundImage = new JLabel(topImg);
		backgroundImage.setBounds(0, 0, topImg.getIconWidth(), topImg.getIconHeight());
		getLayeredPane().add(backgroundImage, Integer.MIN_VALUE);
		
		int lblWidth = 80;
		int txtWidth = 210;
		int comHeight = 25;
		int x = 30;
		int y = topImg.getIconHeight() + 40;
		int marginRight = 15;
		int marginHeight = 40;
		
		JLabel userTypeLbl = new JLabel("用户类型");
		userTypeLbl.setBounds(x, y, lblWidth, comHeight);
		add(userTypeLbl);
		
		userTypeCom = new JComboBox(getUserTypeComboxData());
		userTypeCom.setBounds(x + marginRight + lblWidth, y, txtWidth, comHeight);
		add(userTypeCom);
		
		y += marginHeight;
		
		JLabel userNameLbl = new JLabel("作业人员：");
		userNameLbl.setBounds(x, y, lblWidth, comHeight);
		add(userNameLbl);

		userNameCom = new JComboBox(getUserComboxData());
		userNameCom.setBounds(x + marginRight + lblWidth, y, txtWidth, comHeight);
		add(userNameCom);

		y += marginHeight;
		
		JLabel userPwdLbl = new JLabel("登录密码：");
		userPwdLbl.setBounds(x, y, lblWidth, comHeight);
		add(userPwdLbl);

		userPwdTxt = new JPasswordField();
		userPwdTxt.setBounds(x + lblWidth + marginRight, y, txtWidth, comHeight);
		add(userPwdTxt);
		
		loginBtn = new JButton("登录");
		y = WIN_HEIGHT - 80;
		int btnMarginRight = 120;
		int btnWidth = 70;
		x = topImg.getIconWidth() - btnMarginRight;
		loginBtn.setBounds(x, y, btnWidth, comHeight);
		add(loginBtn);

		x = x - 20 - btnWidth;
		
		exitBtn = new JButton("退出");
		exitBtn.setBounds(x, y, btnWidth, comHeight);
		add(exitBtn);
	}
}